<template>
    <div class="video">
        <div class="edit">
            <div class="top">编辑</div>
            <div class="other">
                <el-form :model="forms" ref="formRef" :rules="rules" label-width="80px" :inline="false" size="normal">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="forms.title"></el-input>
                    </el-form-item>
                    <el-form-item label="封面" prop="cover_img">
                        <el-upload class="avatar-uploader" :action="base_url + '/essay/upload'"
                            :on-success="handleAvatarSuccess" :show-file-list="false">
                            <img v-if="forms.cover_img" :src="base_url + forms.cover_img" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>

                    </el-form-item>
                    <el-form-item label="视频" prop="video_url">
                        <el-upload class="avatar-uploader" accept="mp4" :action="base_url + '/video/upload'"
                            :before-upload="before_uplaod" :on-progress="progress"
                            :on-success="handleAvatarSuccessvideo" :show-file-list="false">
                            <video controls v-if="forms.video_url" :src="base_url + forms.video_url" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <VideoCameraFilled />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="文本" size="normal" prop="rich_text">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" :mode="mode" />
                        <Editor style="height: 350px;width: 100%; overflow-y: hidden;" v-model="valueHtml"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit(formRef)">立即创建</el-button>
                        <el-button @click="router.back()">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>


    </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { reactive, shallowRef, ref } from 'vue';
import { Plus, VideoCameraFilled } from '@element-plus/icons-vue'
import VideoStore from '@/store/VideoStore';
import { type Video } from '@/types/Video';
import { ElMessage, ElLoading, type FormInstance } from 'element-plus'
import { IToolbarConfig } from '@wangeditor/editor'
//@ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useRouter } from 'vue-router';
const router = useRouter()
const store = VideoStore()
const base_url = import.meta.env.VITE_APP_URL
const formRef = ref<FormInstance>()
const forms = reactive<Video>({
    title: "",
    cover_img: "",
    rich_text: "",
    textual: "",
    video_url: "",
    publish_time: Date.now(),
    end_time: Date.now(),
    view: 0,
    likes: [],
    comment: 0
})
let loading: any;
const validateUrl = (rules: any, value: any, callback: any) => {
    rules
    if (value.trim() === '') {
        callback(new Error('请上传'))
    } else {

        callback()
    }
}
const validatorText = (rules: any, value: any, callback: any) => {
    rules
    if (value.trim().length < 10) {
        callback(new Error('简介不能少于10个字符'))
    } else {

        callback()
    }
}
const rules = {
    title: [{ required: true, message: '必填字段', trigger: 'blur' }, { min: 3, message: '至少5个字符', trigger: 'blur' }],
    cover_img: [{ required: true, validator: validateUrl, trigger: 'change' }],
    video_url: [{ required: true, validator: validateUrl, trigger: 'change' }],
    rich_text: [{ required: true, validator: validatorText, trigger: 'blur' }]
}
const onSubmit = (formEl: FormInstance | undefined) => {
    const html = editorRef.value.getHtml()
    const text = editorRef.value.getText()
    forms.rich_text = html
    forms.textual = text
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            await store.video_add(forms)

        } else {
        }
    })
}
const handleAvatarSuccess = (e: any) => {
    forms.cover_img = e.data.url
}
const handleAvatarSuccessvideo = (e: any) => {
    forms.video_url = e.data.url
}
const before_uplaod = (e: any) => {

    if (e.type !== "video/mp4") {
        ElMessage({
            type: "error",
            message: "请上传正确的文件类型"
        })
        return false
    } else {
        loading = ElLoading.service({
            lock: true,
            text: '上传中',
            background: 'rgba(0, 0, 0, 0.7)',
        })

    }

}
const progress = (e: any) => {
    console.log(e)
    if (e.percent == 100) {
        loading.close()
    }
}
//-----富文本-----------
const editorRef = shallowRef()
const mode = ref("default")
// 内容 HTML
const valueHtml = ref('')
const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
const toolbarConfig: Partial<IToolbarConfig> = {
    // const toolbarConfig = {                        
    /* 工具栏配置 */
}
toolbarConfig.excludeKeys = [
    // 排除菜单组，写菜单组 key 的值即可
    'group-video',
    "fullScreen",
    "codeBlock",
    "insertTable",
    "group-image",
    "todo",
    "group-more-style"
]
const editorConfig = {
    placeholder: '请输入内容...', MENU_CONF: {
        'codeSelectLang': {

        },
        "uploadImage": {}
    }
}
</script>

<style lang="scss" scoped>
.video {
    width: 100%;
    display: flex;
    justify-content: center;

    .edit {
        width: 100%;
        background-color: rgba(255, 255, 255, 0.7);
        backdrop-filter: blur(5px);


        .top {
            text-align: center;
            font-size: 1.5vw;
            font-weight: bold;
            margin: 5px 0;
        }

        .other {
            :deep(img) {
                height: 200px;
                width: 200px;
            }

            .avatar-uploader .el-upload {
                border: 1px dashed var(--el-border-color);
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                transition: var(--el-transition-duration-fast);

                video {
                    width: 350px;
                    height: 200px;
                }
            }

            .avatar-uploader .el-upload:hover {
                border-color: var(--el-color-primary);
            }

            .el-icon.avatar-uploader-icon {

                background-color: white;
                font-size: 28px;
                color: #8c939d;
                width: 178px;
                height: 178px;
                text-align: center;
            }
        }


    }
}
</style>